import { Injectable } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  async validateUser(username, password) {
    const findUser = await this.userService.findByName(username);
    if (findUser&& await findUser.comparePassword(password)) {
      return findUser;
    }
    return null;
  }

  async login(user) {
    const payload = {username: user.username, id: user.id};
    return {
      ...payload,
      access_token: this.jwtService.sign(payload),
    };
  }
}
